package run;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import networkTraining.IDataSet;
import networkTraining.IDataSetProvider;

public class SelfOrganizeCenters
{

	public static List<double[]> buildCenterList(int centerCount, IDataSetProvider dataSetProvider, long seed)
	{
		Random rand = new Random();
		IDataSet dataSet = dataSetProvider.getTrainingData();
		int dimension = dataSet.getInputNeuronNames().size();

		List<double[]> centerList = new ArrayList<double[]>();

		double[] center;
		for (int i = 0; i < centerCount; i++)
		{
			center = new double[dimension];
			for (int j = 0; j < dimension; j++)
				center[j] = rand.nextDouble();
			centerList.add(center);
		}

		
		for(int i=0; i<100; i++)
			selfOrganize(dataSet, centerList, dimension, .3);
		
		return centerList;
	}

	public static void selfOrganize(IDataSet dataSet, List<double[]> centerList, int dimension, double learningRate)
	{
		double[] nearest = null;
		double minDistance;
		for (double[] row : dataSet.getDataRowList())
		{
			minDistance = Double.MAX_VALUE;
			
			double[] difference = new double[dimension];
			for(double[] center : centerList)
			{
			
				for(int i=0; i<dimension; i++)
				{
					difference[i] = center[i] - row[i];
				}
				double sum = 0;
				for(int i=0; i<dimension; i++)
				{
					sum += difference[i]* difference[i];
				}
				double distace = Math.sqrt(sum);
				
				if(distace < minDistance)
				{
					minDistance = distace;
					nearest = center;
				}
				
			}
			
			for(int i=0; i<dimension; i++)
			{
				nearest[i] += learningRate*(row[i] - nearest[i]);
			}
		}

	}

}
